package com.eppear.jpfm.framework.tags;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eppear.jpfm.framework.constants.Constants;


/**
 * @author ZJF
 * @Description 授权标签处理类 类似于:
 *              <button class="uk-button uk-button-primary" onclick=
 *              "ddd()">保存</button>
 */
public class AuthTag extends SimpleTagSupport {

	private static final Logger log = LoggerFactory.getLogger(AuthTag.class);

	private String authValue;
	/*private String id;
	private String name;
	private String css;
	private String remark;
	private String style;
	private String onclick;*/

	@Override
	public void doTag() throws JspException, IOException {
		
		boolean hasAuth = this.hasAuth();
		JspWriter out = getJspContext().getOut();
		StringBuffer buf = new StringBuffer();

		if(hasAuth){
			buf.append("");
		}else{
			buf.append("disabled");
		}
		
		try {
			out.write(buf.toString());
			out.flush();
		} catch (IOException e) {
			log.error("授权标签处理标签出错",e);
		}
	}

	public boolean hasAuth() {
		// 不配置权限值的,认为有权限
		if (authValue == null || "".equals(authValue)) {
			return true;
		}

		HttpServletRequest req = (HttpServletRequest) ((PageContext) this.getJspContext()).getRequest();
		HttpSession session = req.getSession();
		Map<Integer, Integer> grantInfoMap = (Map<Integer, Integer>) session.getAttribute(Constants.OPER_AUTH_LIST_KEY);
		// 当前操作的叶子菜单ID
		String currentMenuLeafId = (String) session.getAttribute(Constants.CURRENT_MENU_LEAF_ID);
		if(currentMenuLeafId == null ||"".equals(currentMenuLeafId)) return false;
		
		Integer grantValue = grantInfoMap.get(Integer.valueOf(currentMenuLeafId));
		if (grantValue == null || grantValue == 0) {
			return false;
		}
		Integer rst = grantValue & Integer.valueOf(authValue);
		if (rst > 0) {// 有此权限
			return true;
		}
		return false;
	}
	
	public String getAuthValue() {
		return authValue;
	}

	public void setAuthValue(String authValue) {
		this.authValue = authValue;
	}
	
}
